#include "yuan_mqtt.h"
#include "shm.h"         
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>


// 全局变量：记录消息送达状态
volatile MQTTClient_deliveryToken yuan_deliveredtoken;

// 消息送达确认回调（发布端）
void yuan_delivered(void *context, MQTTClient_deliveryToken dt)
{
    printf("Message with token value %d delivery confirmed\n", dt);
    yuan_deliveredtoken = dt;
}

//消息到达回调（订阅端）
int yuan_msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    int i;
    char* payloadptr = (char*)message->payload;

    printf("Message arrived\n");
    printf("     topic: %s\n", topicName);
    for(i=0; i<message->payloadlen; i++)
    {
        putchar(*payloadptr++);
    }
    putchar('\n');
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return 1;
}

// 连接丢失回调
void yuan_connlost(void *context, char *cause)
{
    printf("\nConnection lost\n");
    printf("     cause: %s\n", cause);
}

// 发布消息函数（单独封装，可传入自定义内容）
int yuan_mqtt_publish(MQTTClient client, const char* payload) 
{
    if (!client || !payload) {
        printf("发布失败：客户端或消息为空\n");
        return -1;
    }

    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    MQTTClient_deliveryToken token;

    char* payload_copy = strdup(payload); // 复制 payload
    
    pubmsg.payload = payload_copy;
    pubmsg.payloadlen = strlen(payload_copy);
    pubmsg.qos = YUAN_QOS;
    pubmsg.retained = 0;

    // 发布消息
    int rc = MQTTClient_publishMessage(client, YUAN_SUB_TOPIC, &pubmsg, &token);
    if (rc != MQTTCLIENT_SUCCESS) {
        printf("发布消息失败，错误码: %d\n", rc);
        return rc;
    }

    // 等待发布确认
    printf("等待发布确认（最多%d秒)...\n", (int)(YUAN_TIMEOUT/1000));
    rc = MQTTClient_waitForCompletion(client, token, YUAN_TIMEOUT);
    if (rc == MQTTCLIENT_SUCCESS) {
        printf("消息发布成功，内容: %s\n", payload);
    } else {
        printf("发布确认超时\n");
    }
    return rc;
}



